import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Post } from '../entities/post.entity';
import { Blog } from '@app/entities';

export interface PublicQuery {
  page?: number;
  limit?: number;
  search?: string;
  tag?: string;
  categoryId?: number;
}

@Injectable()
export class PublicPostsService {
  constructor(
    @InjectRepository(Post, 'kv-blog')
    private readonly postRepository: Repository<Post>,
    @InjectRepository(Blog, 'kv-blog')
    private readonly blogRepository: Repository<Blog>,
  ) { }

  async list(query: PublicQuery) {
    const page = Number(query.page || 1);
    const limit = Math.min(Number(query.limit || 10), 50);

    // 优先从 admin 存的 blogs 表读取（状态=1，未删除）
    const qb = this.blogRepository.createQueryBuilder('blog')
      // 只选择列表所需字段，避免传输 longtext content 造成卡顿
      .select([
        'blog.id',
        'blog.title',
        'blog.summary',
        'blog.cover',
        'blog.author',
        'blog.status',
        'blog.isTop',
        'blog.publishedAt',
        'blog.createdAt',
        'blog.slug',
        'blog.category',
      ]);
    qb.where('blog.status = :status', { status: 1 });
    qb.andWhere('blog.isDeleted = :isDeleted', { isDeleted: false });

    if (query.search) {
      qb.andWhere('(blog.title LIKE :kw OR blog.content LIKE :kw OR blog.summary LIKE :kw)', {
        kw: `%${query.search}%`,
      });
    }

    if (query.categoryId) {
      qb.andWhere('blog.categoryId = :categoryId', { categoryId: query.categoryId });
    }

    if (query.tag) {
      // blogs 表暂未提供 JSON tags，可在未来接入
    }

    // 置顶优先，其次按发布时间/创建时间倒序
    qb.orderBy('blog.isTop', 'DESC');
    qb.addOrderBy('blog.publishedAt', 'DESC');
    qb.addOrderBy('blog.createdAt', 'DESC');

    qb.skip((page - 1) * limit).take(limit);

    const [blogs, total] = await qb.getManyAndCount();
    return {
      posts: blogs,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    };
  }

  async byId(id: number) {
    // blogs 表为数字状态
    const blog = await this.blogRepository.findOne({ where: { id, status: 1, isDeleted: false } });
    if (blog) return blog as any;
    return await this.postRepository.findOne({ where: { id } });
  }

  async bySlug(slug: string) {
    const blog = await this.blogRepository.findOne({ where: { slug, status: 1, isDeleted: false } });
    if (blog) return blog as any;
    return await this.postRepository.findOne({ where: { slug } });
  }
}


